package org.spp.utilities;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * SetUtils.java
 * @author Ilio Catallo, Eleonora Ciceri
 * @version 1.0
 * 
 * Description: the class provides some useful static method to intersect and merge
 *              two lists, find the distinct elements in a list, find the minimum
 *              element in a list of Doubles and compute the mean starting from a list
 *              of Doubles.
 * 
 * Date: Jul 14,2011
 */
public class SetUtils {    
    
    /**
     * Method that returns the intersection between two lists
     * @param a
     * @param b
     * @return 
     */
    public static ArrayList findIntersection(List a, List b) {
        // Variables
        ArrayList intersection = new ArrayList();

        for (Object x : a)
            for (Object y : b)
                if (x.equals(y))
                    intersection.add(x);

        return intersection;
    }
    
    /**
     * Method that returns the union (no duplicates) between two lists
     * @param a
     * @param b
     * @return 
     */
    public static ArrayList findUnion(List a, List b){
        // Variables
        ArrayList union = new ArrayList();
        
        for (Object x : a)
            if (!union.contains(x))
                union.add(x);
           
        for (Object y: b)
            if (!union.contains(y))
                union.add(y);
        
        return union;
    }
    
    /**
     * Method that returns the distinct elements of a list
     * @param a
     * @return 
     */
    public static ArrayList findDistincts(List a){
        // Variables
        ArrayList distinct = new ArrayList();
        
        for (Object x : a)            
            if (!distinct.contains(x))
                distinct.add(x);
        
        return distinct;      
    }
    
    /**
     * Method that finds the minimum element in a list of Doubles
     * @param a
     * @return 
     */
    public static double min(List<Double> a){
        // Variables
        TreeSet tree = new TreeSet<Double>(a);
        
        Double min = (Double)tree.first();
        return min.doubleValue();       
    }
    
    /**
     * Method that computes the mean value fo a list of Doubles
     * @param a
     * @return 
     */
    public static double mean(List<Double> a) {
        // Variables
        double sum = 0;  
        
        for (int i=0; i<a.size(); i++)
            sum += a.get(i);
        
        return sum/a.size();
    }
    
}
